package com.shengqin.controller;

import com.alibaba.excel.EasyExcel;
import com.shengqin.entity.PlanStudent;
import com.shengqin.pojo.student.ExportPlanStudentModel;
import com.shengqin.service.IPlanStudentService;
import com.shengqin.utils.CustomCellWriteWidthConfig;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

@RestController
public class PlanStudentController {
    @Resource
    private IPlanStudentService planStudentService;

    @GetMapping("/admin/v1/exportPlanStudent")
    public void exportStudents(PlanStudent planStudent, HttpServletResponse response) throws IOException {
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("测试", "UTF-8").replaceAll("\\+", "%20");
        List<PlanStudent> studentList = planStudentService.listStudents(planStudent);
        List<ExportPlanStudentModel> exportStudentList = new ArrayList<>();
        studentList.forEach(student -> {
            ExportPlanStudentModel exportStudentModel = new ExportPlanStudentModel();
            BeanUtils.copyProperties(student, exportStudentModel);
            exportStudentList.add(exportStudentModel);
        });
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        EasyExcel.write(response.getOutputStream(), ExportPlanStudentModel.class).registerWriteHandler(new CustomCellWriteWidthConfig()).sheet("考生数据").doWrite(exportStudentList);
    }

}
